var router = require('express').Router();
var util = require('util');
var async = require('async');
var EventProxy = require('eventproxy');

var Consts = require('../consts');
var resultJson = require('../result-json');
var Utils = require('../utils');
var logger = require('../models/logger');
var User = require('../models/User');
var Course = require('../models/Course');
var Teacher = require('../models/Teacher');
var nodeExcel = require('../xls-export');

router.post('/', function(req, res) {
	res.send('respond with a resource');
});

//学生课程
router.post("/listStu", function(req, res) {
	var courses = req.body.course;
	if (!courses)
		return res.send(resultJson(0));

	var results = [];
	var index = 0;
	coursescb(res, index, courses);
})

function coursescb(res, index, courses) {
	if (index == courses.length)
		return res.send(resultJson(0, courses));

	Course.findById(courses[index].id)
		.select("_id name teachers credit photo desc proportion chapter")
		.exec(function(err, course) {
			if (err) {
				logger.error(err);
			}
			if (course) {
				var ids = [];
				for (var i = 0; i < course.teachers.length; i++)
					ids.push(course.teachers[i]._id);

				Teacher.find({
						_id: {
							$in: ids
						}
					},
					function(err, teachers) {
						if (err) {
							logger.error(err);
							return resultJson(2);
						}
						var teachersResult = [];
						for (var i = 0; i < teachers.length; i++) {
							teachersResult.push({
								_id: teachers[i]._id,
								name: teachers[i].name,
								photo: teachers[i].photo
							});
						};
						course.teachers = teachersResult;
						courses[index].result = course;
						index++;
						coursescb(res, index, courses);
					})
			} else {
				index++;
				coursescb(res, index, courses);
			}
		});
};


//查询课程列表 分页 全信息
router.post("/list", function(req, res) {
	var course = req.body;
	var proxy = new EventProxy();
	proxy.all("results", "count", function(results, count) {
		res.send(resultJson(0, {
			results: results,
			count: count
		}))
	});
	var start = course.start || 0;
	var count = course.count || Consts.MAX;
	var sortItem = {
		status: 1
	}
	var item = {};
	if (course.owner)
		item.owner = course.owner;
	if (course.status) {
		item.status = course.status;
		sortItem = {
			name: 1
		};
	}

	if (course.category)
		item.category = course.category;

	Course.find(item).skip(start).limit(count).sort(sortItem).exec(function(err, courses) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		var courses = JSON.parse(JSON.stringify(courses));
		courseCCB(res, 0, courses, proxy);
	});

	Course.find(item).count(function(err, num) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		proxy.emit("count", num);
	});
});

function courseCCB(res, index, courses, proxy) {
	if (index == courses.length)
		return proxy.emit("results", courses);
	User.findById(courses[index].owner, function(err, user) {
		if (err || !user) {
			user = {};
		}
		courses[index].ownerName = user.name;
		User.find({
			"course.id": courses[index]._id
		}).count(function(err, num) {
			if (err || !user) {
				logger.error(err);
				num = 0;
			}
			courses[index].count = num;
			courseTCB(res, index, 0, courses, proxy);
		});
	});
};

function courseTCB(res, index, index2, courses, proxy) {
	if (index2 == courses[index].teachers.length) {
		index++;
		return courseCCB(res, index, courses, proxy);
	}

	Teacher.findById(courses[index].teachers[index2]._id, function(err, user) {
		if (!user)
			user = {};

		courses[index].teachers[index2] = {
			name: user.name,
			photo: user.photo,
			_id: courses[index].teachers[index2]._id
		}
		index2++;
		courseTCB(res, index, index2, courses, proxy);
	});
};


//根据课程id查询课程
router.post("/detail", function(req, res) {
	var course = req.body;
	if (!course._id)
		return res.send(resultJson(3));

	Course.findById(course._id).exec(function(err, course) {
		console.log(course);
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		if (!course)
			return res.send(resultJson(0, {}));

		var course = JSON.parse(JSON.stringify(course));
		User.findById(course.owner, function(err, user) {
			if (err || !user) {
				logger.error(err);
				user = {};
			}
			course.ownerName = user.name;
			var results = [];
			var index = 0;
			if (course.teachers.length == 0)
				res.send(resultJson(0, course));
			coursecb(res, index, course, results);

		})
	})
});

//根据知识点id查询知识点信息
router.post("/detailKnowledge", function(req, res) {
	var _id = req.body._id;
	if (!_id)
		return res.send(resultJson(3));

	Course.findOne({
		"chapter.knowledge._id": _id
	}, {
		"chapter.$.knowledge": 1
	}).exec(function(err, course) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		if (!course)
			return res.send(resultJson(0));
		course = JSON.parse(JSON.stringify(course));
		var result;
		for (var i = 0; i < course.chapter.length; i++) {
			for (var j = 0; j < course.chapter[i].knowledge.length; j++) {
				if (course.chapter[i].knowledge[j]._id == _id) {
					course.chapter[i].knowledge[j].cid = course._id;
					course.chapter[i].knowledge[j].chid = course.chapter[i]._id;
					result = (course.chapter[i].knowledge[j]);
				}
			};
		};
		return res.send(resultJson(0, result));
	})
});

router.post("/detailChapter", function(req, res) {
	var _id = req.body._id;
	if (!_id)
		return res.send(resultJson(3));

	Course.findOne({
		"chapter._id": _id
	}, {
		"chapter.$": 1,
	}).exec(function(err, course) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		if (!course)
			return res.send(resultJson(0));
		var result;
		for (var i = 0; i < course.chapter.length; i++) {
			if (course.chapter[i]._id == _id)
				result = ({
					name: course.chapter[i].name,
					category: course.chapter[i].category,
					desc: course.chapter[i].desc
				});
		};
		return res.send(resultJson(0, result));
	})
});

//查询讲师名称回调函数
function coursecb(res, index, messages, results) {
	if (index == messages.teachers.length)
		return res.send(resultJson(0, messages));
	console.log(messages.teachers[index]);
	Teacher.findById(messages.teachers[index], function(err, teacher) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		if (!teacher)
			teacher = {};

		messages.teachers[index] = teacher
		index++;
		coursecb(res, index, messages, results);
	});
};

//改变状态
router.post("/chengeStatus", function(req, res) {
	var status = req.body.status;
	var _id = req.body._id;
	var rejectDes = req.body.rejectDes;
	Course.update({
		_id: _id
	}, {
		$set: {
			status: status,
			rejectDes: rejectDes
		}
	}).exec(function(err) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		res.send(resultJson(0));
	});
});

//添加 修改课程
router.post("/upsert", function(req, res) {
	var course = req.body;
	course = JSON.stringify(course);
	course = course.replace(/\</g, '&lt;').replace(/\>/g, '&gt;').replace(/</g, '&lt;').replace(/>/g, '&lg;');
	course = JSON.parse(course);

	if (!course.name)
		return res.send(resultJson(3));

	if (course._id) {
		if (course.status == Consts.STATUS.PASS || course.status == Consts.STATUS.REJECT) //通过/拒绝
			course.publish = new Date();
		else if (course.status == Consts.STATUS.VERIFYING) //审核
			course.submit = new Date();

		if (!course.chapter)
			course.chapter = [];

		Course.update({
			_id: course._id
		}, {
			$set: course
		}).exec(function(err, result) {
			if (err) {
				logger.error(err);
				return res.send(resultJson(2));
			}
			return res.send(resultJson(0));

			Course.findById(course._id).exec(function(err, course) {
				if (err) {
					logger.error(err);
					return res.send(resultJson(2));
				}
				if (!course)
					return res.send(resultJson(0, {}));

				var course = JSON.parse(JSON.stringify(course))
				User.findById(course.owner, function(err, user) {
					if (err || !user) {
						logger.error(err);
						user = {}
					}
					course.ownerName = user.name
					var results = [];
					var index = 0;
					if (course.teachers.length == 0)
						res.send(resultJson(0, course));
					coursecb(res, index, course, results);
				});
			});
		});
	} else {
		if (!course.name)
			return res.send(resultJson(3));

		Course.findOne({
			name: course.name
		}).exec(function(err, courses) {
			if (courses)
				return res.send(resultJson(301));

			course.status = Consts.STATUS.UNCOMMIT;
			course.create = new Date();
			new Course(course).save(function(err, course) {
				if (err) {
					logger.error(err);
					return res.send(resultJson(2));
				}
				res.send(resultJson(0, course));
			});
		});
	};
});

//根据课程id推荐和取消推荐
router.post("/recommend", function(req, res) {
	var _id = req.body._id;
	var recommend = req.body.recommend;
	console.log("_id:" + _id + " recommend:" + recommend)
	if (!_id || !recommend)
		return res.send(resultJson(3));

	var query;
	if (recommend == "true")
		query = Course.update({
			_id: _id
		}, {
			$set: {
				recommend: new Date()
			}
		});
	else
		query = Course.update({
			_id: _id
		}, {
			$unset: {
				recommend: 0
			}
		});

	query.exec(function(err) {
		if (err) {
			logger.error(err);
			res.send(resultJson(2));
		} else
			res.send(resultJson(0));
	});
});

//根据课程id删除课程
router.post("/remove", function(req, res) {
	var course = req.body;
	if (!course._id)
		return res.send(resultJson(3));
	Project.count({
		course: course._id
	}).exec(function(err, num) {
		if (num > 0)
			return res.send(resultJson(109));
		Direction.count({
			"courses.id": course._id
		}).exec(function(err, num) {
			if (num > 0)
				return res.send(resultJson(109));
			Course.remove({
				"_id": course._id
			}, function(err) {
				if (err) {
					logger.error(err);
					res.send(resultJson(2));
				} else
					res.send(resultJson(0));
			});
		});
	});

});

//导出视频 地址对应的名称
router.get("/exportUrl2Name", function(req, res) {
	var conf = {};
	var title1 = "用户导出表";
	conf.heads = [];
	conf.cols = [{
		caption: '课程名',
		type: 'string',
	}, {
		caption: '视频名称',
		type: 'string',
	}, {
		caption: '视频地址',
		type: 'string',
	}];

	conf.rows = [];
	Course.find().exec(function(err, courses) {
		var filename = "知识点视频 地址对应名称.xlsx";
		filename = encodeURI(filename);
		for (var i = 0; i < courses.length; i++) {
			var outputs = [];
			outputs.push(courses[i].name || "", "", "");
			conf.rows.push(outputs);
			var video = [];
			for (var j = 0; j < courses[i].chapter.length; j++) {
				for (var m = 0; m < courses[i].chapter[j].knowledge.length; m++) {
					for (var n = 0; n < courses[i].chapter[j].knowledge[m].video.length; n++) {
						video.push(courses[i].chapter[j].knowledge[m].video[n])
					};
				};
			};
			for (var ni = 0; ni < video.length; ni++) {
				conf.rows.push(["", video[ni].name, video[ni].url]);
			};
		};
		var result = nodeExcel.execute(conf);
		res.setHeader('Content-Type', 'application/vnd.openxmlformats');
		res.setHeader("Content-Disposition", "attachment; filename=" + filename);
		return res.end(result, 'binary');
	});
});
//导出视频 地址对应的名称
router.get("/exportUrl2Name2", function(req, res) {
	var conf = {};
	var title1 = "用户导出表";
	conf.heads = [];
	conf.cols = [{
		caption: '课程名',
		type: 'string',
	}, {
		caption: '文档名称',
		type: 'string',
	}, {
		caption: '文档地址',
		type: 'string',
	}];

	conf.rows = [];
	Course.find().exec(function(err, courses) {
		var filename = "知识点文档 地址对应名称.xlsx";
		filename = encodeURI(filename);
		for (var i = 0; i < courses.length; i++) {
			var outputs = [];
			outputs.push(courses[i].name || "", "", "");
			conf.rows.push(outputs);
			var material = [];
			for (var j = 0; j < courses[i].chapter.length; j++) {
				for (var m = 0; m < courses[i].chapter[j].knowledge.length; m++) {
					for (var n = 0; n < courses[i].chapter[j].knowledge[m].material.length; n++) {
						material.push(courses[i].chapter[j].knowledge[m].material[n])
					};
				};
			};
			for (var ni = 0; ni < material.length; ni++) {
				conf.rows.push(["", material[ni].name, material[ni].url]);
			};
		};
		var result = nodeExcel.execute(conf);
		res.setHeader('Content-Type', 'application/vnd.openxmlformats');
		res.setHeader("Content-Disposition", "attachment; filename=" + filename);
		return res.end(result, 'binary');
	});
});
module.exports = router;